﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using Baosight.Platform.Core;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using Baosight.ZNH.ZMCA.UI.Controls;
using Baosight.ZNH.ZMCA.UI.Utils;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;
using Baosight.ZNH.ZMCA.UI.Model;


namespace Baosight.ZNH.ZMCA.UI
{
    /// <summary>
    /// ZMCA83对数据的处理与ZMCA12一样
    /// </summary>
    public partial class ZMCA83 : EFView
    {
        ZMCA83Controler controler = new ZMCA83Controler();
        public ZMCA83()
        {
            InitializeComponent();
            FillGaugeData();
            FillChartData(this.chart);
            FillListViewData();

        }

        private void FillListViewData()
        {
            controler.GetListViewData(lstView);
        }

        private void FillGaugeData()
        {
            controler.GetGaugeData(gauge, this.indexTitle);
        }


        public void FillChartData(RadChart chart)
        {
            controler.GetChartData(chart, this.chartTop5);
        }
    }

    public class ZMCA83Controler
    {
        RadChart gauge;
        RadChart chart;
        RadChart chartTop5;
        RadTreeListView lstView;

        public const int LEVEL = 2;    //显示单位的层级

        private IList<EIRow> Top5Department = new List<EIRow>();


        public ZMCA83Controler()
        {

        }

        #region 刷新昨日井下三违总数前5位

        public void GetGaugeData(RadChart gauge, TextBlock text)
        {
            this.gauge = gauge;
            text.Text = "昨日井下三违";
            //gauge.leftGaugeDescription.Text = "当月(个)";
            //gauge.rightGaugeDescription.Text = "昨日(个)";

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA13");
            eiInfo.Set("method", "queryByIndex");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getGaugeDataCompleted);
        }

        private void getGaugeDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }
            EIInfo eiInfo = e.EIInfo;
            EIBlock result = eiInfo.GetBlock("result");
            EIBlock departmentsResult = eiInfo.GetBlock("queryByDepartment");

            InitPieChart(this.gauge);

            if (departmentsResult != null && departmentsResult.Rows.Count > 0)
            {
                IList<EIRow> resultList = departmentsResult.Rows;
                AddUpToBase(resultList);

                //降序排列，选择指定层级（LEVEL）的单位
                var sortedList = (from n in resultList where (Common.GetIntValue(n["fdDepartmentLevel"]) == LEVEL)
                         orderby (Common.GetIntValue(n["fdKeyId"])) descending select n).ToList<EIRow>();

                List<DataPoint> totalList = new List<DataPoint>();
                Top5Department.Clear();

                EIBlock b = new EIBlock("1");
                Common.AddEIColumnsToEIBlock(b, new string[] {"fdKeyId", "fdDate", 
                    "fdResponseDepartmentId","fdDepartmentName", "fdDepartmentLevel", "fdParentDepartmentId" });

                b.AddRows(sortedList);


                for (int i = 0; i < 5 && sortedList.Count > i; i++)
                {
                    DataPoint dp = new DataPoint();
                    dp.YValue = Common.GetIntValue(sortedList[i]["fdKeyId"]);

                    if (dp.YValue <= 0)
                        continue;

                    dp.XCategory = Common.GetStringValue(sortedList[i]["fdDepartmentName"]);
                    dp.LegendLabel = Common.GetStringValue(sortedList[i]["fdDepartmentName"]);
                    totalList.Add(dp);

                    Top5Department.Add(sortedList[i]);
                }

                if (sortedList.Count > 5)   //计算其他
                {
                    DataPoint other = new DataPoint() { YValue = 0.0 };
                     
                    for (int j = 5; j < sortedList.Count; j++)
                        other.YValue += Common.GetIntValue(sortedList[j]["fdKeyId"]);
                    other.XCategory = "其他";
                    other.LegendLabel = "其他";
                    if (other.YValue > 0) totalList.Add(other);
                }

                this.gauge.ItemsSource = null;
                this.gauge.ItemsSource = totalList;
            }

            //gauge.leftControler.IsReverse = true;
            //gauge.rightControler.IsReverse = true;
        }

        private void InitPieChart(RadChart PieChart)
        {
            //分布图
            Common.ClearChart(PieChart);
            PieChart.DefaultView.ChartTitle.Visibility = Visibility.Collapsed;
            PieChart.DefaultView.ChartLegend.Header = "";
            PieChart.DefaultView.ChartLegend.FontSize = 10;
            PieChart.DefaultView.ChartLegendPosition = Telerik.Windows.Controls.Dock.Right;

            SeriesMapping pieSeries = new SeriesMapping();
            PieSeriesDefinition pieSeriesDef = new PieSeriesDefinition();
            pieSeries.SeriesDefinition = pieSeriesDef;
            //sm2.LegendLabel = "单位";

            pieSeries.ItemMappings.Add(new ItemMapping("XCategory", DataPointMember.XCategory));
            pieSeries.ItemMappings.Add(new ItemMapping("YValue", DataPointMember.YValue));
            pieSeries.ItemMappings.Add(new ItemMapping("LegendLabel", DataPointMember.LegendLabel));

            pieSeriesDef.InteractivitySettings.HoverScope = InteractivityScope.Item;
            pieSeriesDef.InteractivitySettings.SelectionScope = InteractivityScope.Item;
            pieSeriesDef.InteractivitySettings.SelectionMode = ChartSelectionMode.Single;
            pieSeriesDef.LegendDisplayMode = LegendDisplayMode.DataPointLabel;

            PieChart.SeriesMappings.Add(pieSeries);
        }

        private void AddUpToBase(IList<EIRow> list)
        {
            foreach (var item in list)       //累计运算
            {
                if (Common.GetIntValue(item["fdDepartmentLevel"]) == 1)    //只对LEVEL = 1的层级进行累加
                    AddUp(item, list);
            }
        }

        private void AddUp(EIRow item, IList<EIRow> list)
        {
            string fdDepartmentId = item["fdResponseDepartmentId"].ToString().Trim();
            var childItems = (from element in list where (element["fdParentDepartmentId"] != null) &&
                                  (element["fdParentDepartmentId"].ToString().Trim().Equals(fdDepartmentId))
                              select element).ToList<EIRow>();

            foreach (var it in childItems)
            {
                AddUp(it, list);

                int itemValue = Common.GetIntValue(item["fdKeyId"]);
                int childValue = Common.GetIntValue(it["fdKeyId"]);
                item.Add("fdKeyId", itemValue + childValue);
            }
        }

        #endregion

        #region 刷新RadChart图数据

        public void GetChartData(RadChart chart, RadChart chartTop5)
        {
            this.chart = chart;
            this.chartTop5 = chartTop5;

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA13");
            eiInfo.Set("method", "queryByChart");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getChartDataCompleted);
        }

        private void getChartDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }
            EIInfo eiInfo = e.EIInfo;
            EIBlock queryByYear = eiInfo.GetBlock("queryByYear");
            EIBlock queryByYearClassify = eiInfo.GetBlock("queryByYearClassify");
            int currentMonth = Common.GetIntValue(eiInfo.Get("month"));
            int currentYear = Common.GetIntValue(eiInfo.Get("year"));


            chart.DefaultView.ChartTitle.Content = currentYear + "全矿井下三违类别趋势分析";
            chart.DefaultSeriesDefinition.ShowItemToolTips = true;
            chart.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;
            
            chart.DefaultView.ChartLegend.Header = string.Empty;

            this.chart.DefaultView.ChartTitle.FontSize = Common.FontsizeSetting + 2;
            this.chart.DefaultView.ChartArea.FontSize = Common.FontsizeSetting;
            this.chart.DefaultView.ChartLegend.FontSize = Common.FontsizeSetting - 2;

            this.chart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            this.chart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            this.chart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            SeriesMapping sm1 = new SeriesMapping();
            BarSeriesDefinition totalBar = new BarSeriesDefinition();
            sm1.SeriesDefinition = totalBar;
            sm1.LegendLabel = "Bar Series";
            sm1.CollectionIndex = 0;
            sm1.LegendLabel = "三违总数";

            sm1.SeriesDefinition.ShowItemLabels = false;
            sm1.SeriesDefinition.ShowItemToolTips = true;
            sm1.SeriesDefinition.ShowZeroValuesLabels = true;

            sm1.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
            sm1.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));

            sm1.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
            sm1.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
            sm1.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;

            chart.SeriesMappings.Add(sm1);

            List<List<ChartData>> itemsSource = new List<List<ChartData>>();
            List<ChartData> totalList = new List<ChartData>();
            for (int i = 1; i <= currentMonth; i++)
            {
                totalList.Add(new ChartData(i + "月", 0));
            }
            foreach (var item in queryByYear.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }
                AddChartDate(item, date, totalList);
            }
            itemsSource.Add(totalList);

            GetClassData(queryByYearClassify, currentMonth, itemsSource);

            chart.ItemsSource = itemsSource;
        }

        private void GetClassData(EIBlock queryByYearClassify, int currentMonth, List<List<ChartData>> itemsSource)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (var item in queryByYearClassify.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                if (!dic.ContainsKey(item["fdClassify"].ToString()))
                {
                    List<ChartData> levelList = new List<ChartData>();
                    for (int i = 1; i <= currentMonth; i++)
                    {
                        levelList.Add(new ChartData(i + "月", 0));
                    }
                    itemsSource.Add(levelList);
                    dic.Add(item["fdClassify"].ToString(), itemsSource.Count - 1);

                    SeriesMapping sm2 = new SeriesMapping();
                    SplineSeriesDefinition d2 = new SplineSeriesDefinition();
                    sm2.SeriesDefinition = d2;
                    sm2.LegendLabel = item["fdClassify"].ToString();
                    sm2.CollectionIndex = itemsSource.Count - 1;

                    sm2.SeriesDefinition.ShowItemLabels = false;
                    sm2.SeriesDefinition.ShowItemToolTips = true;
                    sm2.SeriesDefinition.ShowZeroValuesLabels = true;
                    sm2.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
                    sm2.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
                    sm2.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
                    sm2.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
                    sm2.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;

                    chart.SeriesMappings.Add(sm2);
                }
                List<ChartData> tList = itemsSource[dic[item["fdClassify"].ToString()]];

                AddChartDate(item, date, tList);
            }
        }

        private static void AddChartDate(EIRow item, string date, List<ChartData> tList)
        {
            if (date[5] == '0')
            {
                date = date.Substring(6);
            }
            else
            {
                date = date.Substring(5);
            }
            {
                tList[Common.GetIntValue(date) - 1].DataValue = Common.GetDecimalValue(item["fdKeyId"].ToString());
            }
        }

        #endregion

        #region 刷新RadListView区域数据

        public void GetListViewData(RadTreeListView lstView)
        {
            this.lstView = lstView;
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA13");
            eiInfo.Set("method", "queryByListView");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getListViewDataCompleted);
        }

        private void getListViewDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }

            EIInfo eiInfo = e.EIInfo;
            EIBlock queryByYear = eiInfo.GetBlock("queryByYear");
            EIBlock queryByDepartment = eiInfo.GetBlock("queryByDepartment");
            EIBlock queryByListC = eiInfo.GetBlock("queryByListC");

            int currentMonth = Common.GetIntValue(eiInfo.Get("month"));
            int currentYear = Common.GetIntValue(eiInfo.Get("year"));


            for (int i = 12 - currentMonth + 2; i > 2; i--)
            {
                var cl = lstView.Columns[i];
                cl.IsVisible = false;
            }

            List<ZMCA12DetailItem> itemsSource = new List<ZMCA12DetailItem>();

            ZMCA12DetailItem yearItem = new ZMCA12DetailItem();
            ZMCA12DetailItem yearDepartmentItem = new ZMCA12DetailItem();
            ZMCA12DetailItem yearClassifyItem = new ZMCA12DetailItem();

            itemsSource.Add(yearItem);
            Type itemType = yearItem.GetType();
            yearItem.Name = "全矿";
            yearClassifyItem.Name = "所有类别";
            yearItem.Items.Add(yearClassifyItem);
            yearDepartmentItem.Name = "所有单位";
            yearItem.Items.Add(yearDepartmentItem);

            foreach (var item in queryByYear.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Length == 10)
                {
                    yearItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    yearClassifyItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    //yearDepartmentItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                if (date[5] == '0')
                {
                    date = date.Substring(6);
                }
                else
                {
                    date = date.Substring(5);
                }

                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(yearItem, Common.GetIntValue(item["fdKeyId"]), null);
                pi.SetValue(yearClassifyItem, Common.GetIntValue(item["fdKeyId"]), null);
                //pi.SetValue(yearDepartmentItem, Common.GetIntValue(item["fdKeyId"]), null);
            }

            AddChildItemByBlock(queryByListC, yearClassifyItem, itemType, "fdClassify");
            AddDepartmentChildItemByBlock(queryByDepartment, yearDepartmentItem, itemType);

            lstView.ItemsSource = itemsSource;
        }

        private static void AddChildItemByBlock(EIBlock block, ZMCA12DetailItem parentDetailItem, Type itemType, string columnName)
        {
            ZMCA12DetailItem detailItem = null;
            foreach (var item in block.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                string itemName = item[columnName].ToString();
                if (detailItem == null || detailItem.Name != itemName)
                {
                    detailItem = new ZMCA12DetailItem();
                    parentDetailItem.Items.Add(detailItem);
                    detailItem.Name = itemName;
                }

                if (date.Length == 10)
                {
                    detailItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                if (date[5] == '0')
                {
                    date = date.Substring(6);
                }
                else
                {
                    date = date.Substring(5);
                }

                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }
        }

        private void AddDepartmentChildItemByBlock(EIBlock block, ZMCA12DetailItem parentDetailItem, Type itemType)
        {
            Dictionary<string, ZMCA12DetailItem> dic = new Dictionary<string, ZMCA12DetailItem>();
            ZMCA12DetailItem detailItem = null;
            foreach (var item in block.Rows)
            {
                string date = Common.GetStringValue(item["fdDate"]);
                if (item["fdDate"] != null && date.Trim() == string.Empty)
                {
                    continue;
                }

                string itemUniqueName = Common.GetStringValue(item["fdResponseDepartmentId"]);
                if (detailItem == null || detailItem.UniqueName != itemUniqueName)
                {
                    detailItem = new ZMCA12DetailItem();
                    dic.Add(itemUniqueName, detailItem);
                    if (Common.GetIntValue(item["fdDepartmentLevel"]) == 1)
                    {
                        parentDetailItem.Items.Add(detailItem);
                    }
                    else
                    {
                        if (dic.ContainsKey(item["fdParentDepartmentId"].ToString()))
                        {
                            dic[item["fdParentDepartmentId"].ToString()].Items.Add(detailItem);
                        }
                        else
                        {
                            parentDetailItem.Items.Add(detailItem);
                            //单位层级有问题，找不到父亲单位
                        }
                    }
                    detailItem.UniqueName = itemUniqueName;

                    detailItem.Name = item["fdDepartmentName"].ToString();
                }

                if (date == string.Empty)
                {
                    continue;
                }
                else if (date.Length == 10)
                {
                    detailItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                if (date[5] == '0')
                {
                    date = date.Substring(6);
                }
                else
                {
                    date = date.Substring(5);
                }

                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }
            ZMCA12DetailItem.SummarizedChildItemData(parentDetailItem);

            //查询、绘制当月三违数量前五个单位的趋势图
            IDictionary<EIRow, ZMCA12DetailItem> chartDic = new Dictionary<EIRow, ZMCA12DetailItem>();

            if (Top5Department.Count > 0)
            {
                for(int i = 0; i < Top5Department.Count; i++)
                    chartDic.Add(Top5Department[i], dic[Common.GetStringValue(Top5Department[i]["fdResponseDepartmentId"])]);

                ShowTop5Trend(chartDic);
            }
        }

        #endregion

        #region 查询前5个单位的趋势

        private void ShowTop5Trend(IDictionary<EIRow, ZMCA12DetailItem> dic)
        {
            int currentYear = DateTime.Today.Year;
            int currentMonth = DateTime.Today.Month;

            this.chartTop5.DefaultView.ChartTitle.FontSize = Common.FontsizeSetting;
            this.chartTop5.DefaultView.ChartArea.FontSize = Common.FontsizeSetting;
            this.chartTop5.DefaultView.ChartLegend.FontSize = Common.FontsizeSetting;

            this.chartTop5.DefaultView.ChartTitle.Content = currentYear + "年" + currentMonth + "月三违数量前五个单位三违趋势分析";
            this.chartTop5.DefaultSeriesDefinition.ShowItemToolTips = true;
            this.chartTop5.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;
            this.chartTop5.DefaultView.ChartLegend.Header = "";

            this.chartTop5.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            this.chartTop5.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            this.chartTop5.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            List<List<ChartData>> tendChartItemsSource = new List<List<ChartData>>();

            for (int i = 0; i < dic.Count; i++)
            {
                this.chartTop5.SeriesMappings.Add(GenerateSeriesForChart(Common.GetStringValue(
                    Top5Department[i]["fdDepartmentName"]), i, "Line Series"));

                ZMCA12DetailItem item = dic[Top5Department[i]];
                Type itemType = item.GetType();
                List<ChartData> lst = new List<ChartData>();

                for (int j = 1; j <= currentMonth; j++)
                {
                    lst.Add(new ChartData(j + "月", 0));
                    PropertyInfo pi = itemType.GetProperty("M" + j.ToString());
                    lst[j - 1].DataValue = Common.GetIntValue(pi.GetValue(item, null));
                }

                tendChartItemsSource.Add(lst);

            }

            this.chartTop5.ItemsSource = tendChartItemsSource;
        }

        private SeriesMapping GenerateSeriesForChart(string label, int index, string defType)
        {
            SeriesMapping series = new SeriesMapping();

            switch (defType)
            {
                case "Bar Series":
                    series.SeriesDefinition = new BarSeriesDefinition();
                    break;
                case "Line Series":
                    series.SeriesDefinition = new LineSeriesDefinition();
                    break;
                case "Spline Series":
                    series.SeriesDefinition = new SplineSeriesDefinition();
                    break;
                default:
                    break;
            }

            series.CollectionIndex = index;
            series.LegendLabel = label;

            series.SeriesDefinition.ShowItemLabels = false;
            series.SeriesDefinition.ShowItemToolTips = true;
            series.SeriesDefinition.ShowZeroValuesLabels = true;

            series.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
            series.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));

            series.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
            series.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
            series.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;
            series.SeriesDefinition.LegendDisplayMode = LegendDisplayMode.SeriesLabel;

            return series;
        }

        #endregion

    }
}